import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

/* AxiosData */
import Axios from 'axios'
import Qs from 'qs'

/* CityData */
import _CityData from '@/assets/ts/city.data-3.ts'
/* 引入storeCookie */
import _Store from '@/assets/ts/localStorage.ts'
/* 引入全局自定义变量 */
import _Global from '@/assets/ts/Global.ts'
/* 引入公用函数 */
import _Myfun from '@/assets/ts/Myfun.ts'
/* 引入微信jsddk */
import _Wxtool from '@/assets/ts/wxjsapi.ts'
/* 引入腾讯地图定位组件 */
import _Qqmap from '@/assets/ts/qqmap.ts'
/* 引入OSS */
import _Ossup from '@/assets/ts/OSS.ts'

/* forComponent */
import CropPer from '@/components/cropper.vue'
import Esign from '@/components/esign.vue'
import Layer from '@/components/layer.vue'
import PicKer from '@/components/picKer.vue'
import PicKerMore from '@/components/pickermore.vue'
import PickerDate from '@/components/pickerdate.vue'
import PreviewImg from '@/components/previewimg.vue'
import SideBar from '@/components/sidebar.vue'
import SliDing from '@/components/sliding.vue'
import SlidEvent from '@/components/slidevent.vue'
import SlidPage from '@/components/slidpage.vue'
import Stamp from '@/components/stamp.vue'
import Tabs from '@/components/tabs.vue'
import Tabfix from '@/components/tabfix.vue'
import UploadOss from '@/components/uploadoss.vue'
import singleFormMoreUploadoss from '@/components/singleFormMoreUploadoss.vue'

/* *** */
let _Fees = []
const isNumber = /^[0-9]+.?[0-9]*/

/* 创建实例 */
const app = createApp(App)

/* 使用自定义组件 */
app.component('cropper-view', CropPer)
app.component('esign-view', Esign)
app.component('layer-view', Layer)
app.component('picker-view', PicKer)
app.component('pickermore-view', PicKerMore)
app.component('pickerdate-view', PickerDate)
app.component('preImg-view', PreviewImg)
app.component('sidebar-view', SideBar)
app.component('sliding-view', SliDing)
app.component('slidevent-view', SlidEvent)
app.component('slidpage-view', SlidPage)
app.component('stamp-view', Stamp)
app.component('tabs-view', Tabs)
app.component('tabfix-view', Tabfix)
app.component('uploadoss-view', UploadOss)
app.component('uploadoss-moreField', singleFormMoreUploadoss)

/* 设置扩展属性 */
app.config.globalProperties.$City = _CityData
app.config.globalProperties.$Store = _Store
app.config.globalProperties.$Global = _Global
app.config.globalProperties.$Myfun = _Myfun
app.config.globalProperties.$WxTool = _Wxtool
app.config.globalProperties.$QQMap = _Qqmap
app.config.globalProperties.$OssUp = _Ossup

/* 获取api服务器地址 */
const serverSrc = window.location.protocol + '//' + _Global.dateSrc + '/' + _Global.modulename + '/'

/* 获取网络地址信息 */
app.config.globalProperties.$imageSrc = window.location.protocol + '//' + _Global.picSrc
app.config.globalProperties.$siteSrc = window.location.protocol + '//' + _Global.siteSrc

/* ForAxiosOne */
const HTTP = Axios.create({
  baseURL: serverSrc,
  transformRequest: [(data) => {
    data = Qs.stringify(data)
    return data
  }],
  withCredentials: true,
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
HTTP.interceptors.response.use((res) => { return res.data }, (err) => {
  if (err) return Promise.reject('网络出现异常！！！')
})
app.config.globalProperties.$http = HTTP
/* ForAxiosAll */
Axios.defaults.baseURL = serverSrc
Axios.defaults.withCredentials = true
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
Axios.defaults.transformRequest = (data) => {
  data = Qs.stringify(data)
  return data
}
Axios.interceptors.response.use((res) => { return res.data }, (err) => {
  if (err) return Promise.reject('网络出现异常！！！')
})
app.config.globalProperties.$Axios = Axios

/* --设置底部tab高亮栏目-- */
const setHighLighted = (items) => {
  let forindex = 0
  if (items && Number(items.length) > 0) {
    let newItems = []
    router.options.routes.some((current) => {
      if (String(current.name) === String(items[0].name)) newItems = current.children
    })
    if (items[1]) {
      newItems.some((current, index) => {
        if (String(current.name) === String(items[1].name)) forindex = index
      })
    }
  }
  app.config.globalProperties.$Forindex = forindex
}

/* 微信授权同意和拒绝处理 */
const setAuthorization = async (to) => {
  if (_Store.get('wz_module') !== _Global.modulename) {
    _Store.set('wz_module', _Global.modulename)
    await HTTP.get('oauth/get-redirect-url', {
      params: { redirectUrl: window.location.origin + to.fullPath }
    }).then((res) => {
      if (res) window.location.href = res
    }).catch((err) => { window.console.log(err) })
  } else {
    await HTTP.get('oauth/get-current-user').then((res) => {
      _Store.set('userInfo', res)
    }).catch((err) => {
      const forClick = _Store.get('forClick')
      _Store.clear(() => {
        _Store.set('forClick', forClick)
      })
    })
    // ----
    if (_Store.get('logUser')) {
      // --检查是否被挤下线--
      await HTTP.post('wechat/get-current-dealer', {
        is_stoped: 2,
        // ----
        config_id: _Store.get('userInfo').config_id,
        openid: _Store.get('userInfo').openid
      }).then((res) => {
        if (res.success && res.datainfo) {
          _Store.set('logUser', res.datainfo)
          _Store.set('SN', res.datainfo.sn)
        } else if (to.meta.power) {
          // --被登录后清空本地缓存，有登录要求重新登录--
          const wzModule = _Store.get('wz_module')
          const forClick = _Store.get('forClick')
          _Store.clear(() => {
            _Store.set('wz_module', wzModule)
            _Store.set('forClick', forClick)
            // ----
            router.push({ name: 'UserLogin' })
          })
        } else {
          // --被登录后清空本地缓存，无登录要求停留在本页--
          const wzModule = _Store.get('wz_module')
          const forClick = _Store.get('forClick')
          _Store.clear(() => {
            _Store.set('wz_module', wzModule)
            _Store.set('forClick', forClick)
          })
        }
      }).catch((err) => { window.console.log(err) })
    }
  }
}

/* 获取微信分享参数 */
const getWXconfig = async (to) => {
  const backurl = window.location.origin + to.fullPath
  if ((_Store.get('WXConfig') && String(_Store.get('WXConfig').url) !== String(backurl)) || !_Store.get('WXConfig')) {
    await HTTP.get('config/js-sdk-config', {
      params: { url: backurl }
    }).then((res) => {
      if (res) _Store.set('WXConfig', res)
    }).catch((err) => { window.console.log(err) })
  }
}

/* 获取后台相关设置 */
const getClubOne = async () => {
  const forSysData = {
    params: {
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  await Axios.all([
    Axios.get('system/index', forSysData)
  ]).then(Axios.spread((sysData) => {
    const SData = sysData.items
    // --系统通用设置--
    app.config.globalProperties.$Sys = SData
    // --指定手机号--
    const phoneItems = SData.filter((item) => { return String(item.name) === 'specify_phone' })
    if (Number(phoneItems.length) === 1) app.config.globalProperties.$Phone = phoneItems[0].value
    // --系统默认设置--
    const sysItems = SData.filter((item) => { return String(item.name) === 'market_service' })
    if (Number(sysItems.length) === 1) {
      _Myfun.getJsonData(sysItems[0].value, (resJson) => {
        if (Number(resJson.length) > 0) {
          const MRData = resJson[0]
          // ----
          app.config.globalProperties.$Init = resJson[0]
          // ----
          app.config.globalProperties.$imgLoad = ''
          app.config.globalProperties.$imgEwm = ''
          if (MRData.load && MRData.load[0]) app.config.globalProperties.$imgLoad = MRData.load[0].image
          if (MRData.wechat_img && MRData.wechat_img[0]) app.config.globalProperties.$imgEwm = MRData.wechat_img[0].image
          app.config.globalProperties.$telPhone = _Myfun.setText(MRData.telphone)
          // ----
          app.config.globalProperties.$shareTitle = _Myfun.setText(MRData.share_title)
          app.config.globalProperties.$shareDesc = _Myfun.setText(MRData.share_desc)
          app.config.globalProperties.$shareIcon = MRData.logo && MRData.logo[0] ? MRData.logo[0].image : ''
        }
      })
    }
    // --获取组织会费--
    const feeItems = SData.filter((item) => { return String(item.name) === 'fees_name' })
    if (Number(feeItems.length) === 1) {
      _Myfun.getJsonData(feeItems[0].value, (resJson) => {
        if (Number(resJson.length) > 0) {
          _Fees = resJson
          app.config.globalProperties.$Fees = resJson
        }
      })
    }
    // --获取定制功能信息--
    const customItems = SData.filter((item) => { return String(item.name) === 'market_customFuncUser' })
    if (Number(customItems.length) === 1) {
      _Myfun.getJsonData(customItems[0].value, (resJson) => {
        if (Number(resJson.length) > 0) app.config.globalProperties.$Custom = resJson[0]
      })
    }
  })).catch((err) => { window.console.log(err) })
}

/* 检查系统充值是否开启关闭 */
const checkFeeUse = (feeId) => {
  let forFeeUse = true
  _Fees.some((item) => {
    if (String(item.id) === String(feeId)) forFeeUse = item.isOpenUse
  })
  return forFeeUse
}

/* 检查用户充值是否过期 */
const checkDeadLine = async () => {
  if (_Store.get('logUser')) {
    const curDate = Date.parse(new Date())
    const forLogUser = _Store.get('logUser')
    // --充值有效期--
    let workLine = []
    _Myfun.getJsonData(forLogUser.topupze, (resJson) => { workLine = resJson })
    if (Number(workLine.length) > 0) {
      // --购买门店租金有效期--
      await getWorkLine(workLine, 'marketing', 0, {
        type: 'patch',
        url: 'dealer/update?id=' + forLogUser.id,
        data: {
          is_store: 0,
          // ----
          config_id: _Store.get('userInfo').config_id,
          openid: _Store.get('userInfo').openid
        }
      }, (res) => { _Store.set('logUser', res) })
      // --批发分销有效期--
      await getWorkLine(workLine, 'marketRent', 0, {
        type: 'patch',
        url: 'dealer/update?id=' + forLogUser.id,
        data: {
          is_retail: 0,
          // ----
          config_id: _Store.get('userInfo').config_id,
          openid: _Store.get('userInfo').openid
        }
      }, (res) => { _Store.set('logUser', res) })
      // --开仓分销有效期--
      await getWorkLine(workLine, 'cloudRent', 0, {
        type: 'patch',
        url: 'dealer/update?id=' + forLogUser.id,
        data: {
          is_cloud: 0,
          // ----
          config_id: _Store.get('userInfo').config_id,
          openid: _Store.get('userInfo').openid
        }
      }, (res) => { _Store.set('logUser', res) })
      // --我要赞助有效期--
      await getWorkLine(workLine, 'sponsorPush', 0, {
        type: 'get',
        url: 'meeting-organiser/index',
        data: {
          params: { 'MeetingOrganiserSearch[dealer_id]': forLogUser.id }
        }
      }, async (res) => {
        if (Number(res.items.length) > 0) {
          await setPublicInfo({
            type: 'patch',
            url: 'meeting-organiser/update?id=' + res.items[0].id,
            data: {
              status: 2,
              // ----
              config_id: _Store.get('userInfo').config_id,
              openid: _Store.get('userInfo').openid
            }
          })
        }
      })
    }
    // --功能有效期--
    let funcLine = []
    _Myfun.getJsonData(forLogUser.topuptw, (resJson) => { funcLine = resJson })
    if (Number(funcLine.length) > 0) {
      // --申请联合运营商有效期--
      await getWorkLine(funcLine, 'operat', '', {
        type: 'patch',
        url: 'dealer/update?id=' + forLogUser.id,
        data: {
          is_agent: 0,
          // ----
          is_saler: 0,
          is_salesman: 0,
          is_exhibition: 0,
          // ----
          topupth: '',
          topuptw: JSON.stringify([{isRecord:1}]),
          // ----
          config_id: _Store.get('userInfo').config_id,
          openid: _Store.get('userInfo').openid
        }
      }, (res) => {
        _Store.set('logUser', res)
        // --是否区域运营商，否则清空代理地区--
        const forIsAgent = funcLine.some((oneItem) => {
          if (String(oneItem.name) === 'salesman') return true
        })
        if (forIsAgent) setPublicInfo({
          type: 'get',
          url: 'agent-set/index',
          data: {
            params: {
              'AgentSetSearch[dealer_id]': forLogUser.id,
              // ----
              sort: 'SORT_DESC'
            }
          }
        }, async (agentRes) => {
          for (let i = 0; i < Number(agentRes.items.length); i++) {
            const agentItem = agentRes.items[i]
            await setPublicInfo({
              type: 'delete',
              url: 'agent-set/delete?id=' + agentItem.id,
              data: {
                config_id: _Store.get('userInfo').config_id,
                openid: _Store.get('userInfo').openid
              }
            })
          }
        })
      })
    }
  }
}
const getWorkLine = async (items, feeId, payId, options, callback) => {
  let amountDate = 0
  const curDate = Date.parse(new Date())
  const forItems = items || []
  if (isNumber.test(payId)) {
    forItems.some((oneItem) => {
      if (String(oneItem.id) === String(feeId)) {
        oneItem.info.some((twoItem) => {
          if (String(twoItem.id) === String(payId)) amountDate = Date.parse(new Date(twoItem.endtime.replace(/-/g, '/'))) || 0
        })
      }
    })
  } else {
    forItems.some((oneItem) => {
      if (String(oneItem.name) === String(feeId)) amountDate = Date.parse(new Date(oneItem.endtime.replace(/-/g, '/'))) || 0
    })
  }
  if (Number(amountDate) < Number(curDate) && Number(amountDate) > 0 && checkFeeUse(feeId)) await setPublicInfo(options, async (res) => { await callback && callback(res) })
}
const setPublicInfo = async (item, callback) => {
  await HTTP[item.type](item.url, item.data).then((res) => {
    if (res) callback && callback(res)
  }).catch((err) => { window.console.log(err) })
}

/* 检查定制功能是否开通 */
const checkCustomFunc = (item, meta) => {
  const forTelphone = _Store.get('logUser').telphone
  const forCustom = app.config.globalProperties.$Custom || {}
  let isCustom = false
  if (forCustom[item]) {
    isCustom = forCustom[item].some((current) => {
      if (String(current.telphone) === String(forTelphone)) return true
    })
  }
  if (meta[item] && !isCustom) return true
}

/* --全局前置守卫设置页面meta-- */
router.beforeEach(async (to, from, next) => {
  // ----
  setHighLighted(to.matched)
  // --上一个组件的title--
  app.config.globalProperties.$Source = document.title
  // --IOS不支持CSS伪类的处理--
  document.body.addEventListener('touchstart', () => {})
  // --路由发生变化修改页面title--
  if (to.meta.title) document.title = to.meta.title
  // --邀请商友sn--
  if (to.query.sn) _Store.set('SN', to.query.sn)
  /* --获取指向路径-- */
  if (String(to.name) !== 'UserLogin') app.config.globalProperties.$forToPage = to.name
  // --检查是否登录--
  if (to.meta.power && !_Store.get('logUser')) router.push({ name: 'UserLogin', query: to.query })
  // ----
  await setAuthorization(to)
  // ----
  await getWXconfig(to)
  // ----
  await getClubOne()
  // ----
  await checkDeadLine()
  // --登录用户操作权限--
  if (_Store.get('logUser')) {
    const forNoAdmin = String(_Store.get('logUser').telphone) !== String(app.config.globalProperties.$Phone)
    if (((to.meta.admin || (to.meta.shop && (!_Store.get('logUser').is_store || Number(_Store.get('logUser').is_store) === 0) && checkFeeUse('marketing')) || (to.meta.func && (!_Store.get('logUser').is_agent || Number(_Store.get('logUser').is_agent) === 0))) && forNoAdmin) || (checkCustomFunc('material', to.meta) || checkCustomFunc('album', to.meta) || checkCustomFunc('wholesaler', to.meta) || checkCustomFunc('contract', to.meta))) router.push({ name: 'UcenTer' })
  }
  // ----
  next()
})

app.use(router).mount('#app')